package com.lagou.myblog.filter;

import com.lagou.myblog.controller.PageLocationController;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 页面跳转URI过滤器
 * 该类的主要作用是为了解析页面html的请求，根据请求地址，转发到相同的请求来解析
 * Creat by jaden.liu
 * 2019/09/09
 */
@Component
public class PageUriFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String requestURI = request.getRequestURI();
        //html请求路径映射到controller
        if (requestURI.endsWith(".html")) {
            String url_prefix = requestURI.substring(1).replace(".html", "");//url前缀
            request.setAttribute(PageLocationController.PAGE_PATH_ATTR, url_prefix);
            request.getRequestDispatcher("/api/pub/page.action").forward(servletRequest, servletResponse);
        } else {
            //进入下一个过滤器
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {
    }

}
